package cn.bby.query.server.domain.share.util;

import cn.bby.query.server.domain.agg.sys.repository.HealthInfoRepository;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author ben
 * @since 2025/4/19 00:28
 */
@Component
@Slf4j
public class ErrorLogUtil {
    @Resource
    private HealthInfoRepository healthInfoRepository;
    static JsonFactory factory = new JsonFactory();

    public static void main(String[] args) throws IOException {
        String json = "{\"name\":\"李四\",\"age\":30,\"skills\":[\"Java\",\"Python\"]}";
        JSON.parseObject(json).get("source");
        JSON.parseObject(json, Cc.class);
        String val = "{\"schema\":{\"type\":\"struct\",\"fields\":[{\"type\":\"struct\",\"fields\":[{\"type\":\"int64\",\"optional\":false,\"default\":0,\"field\":\"id\"},{\"type\":\"string\",\"optional\":false,\"field\":\"tenant_id\"},{\"type\":\"int64\",\"optional\":false,\"field\":\"goods_id\"},{\"type\":\"string\",\"optional\":false,\"field\":\"name\"},{\"type\":\"bytes\",\"optional\":false,\"name\":\"org.apache.kafka.connect.data.Decimal\",\"version\":1,\"parameters\":{\"scale\":\"2\",\"connect.decimal.precision\":\"10\"},\"field\":\"price\"},{\"type\":\"string\",\"optional\":false,\"field\":\"description\"},{\"type\":\"string\",\"optional\":false,\"field\":\"seller_phone\"},{\"type\":\"int64\",\"optional\":false,\"default\":0,\"field\":\"create_time\"},{\"type\":\"int64\",\"optional\":false,\"default\":0,\"field\":\"update_time\"},{\"type\":\"string\",\"optional\":false,\"field\":\"created_by\"},{\"type\":\"string\",\"optional\":false,\"field\":\"updated_by\"}],\"optional\":true,\"name\":\"topic-query_example-1.public.goods_info.Value\",\"field\":\"before\"},{\"type\":\"struct\",\"fields\":[{\"type\":\"int64\",\"optional\":false,\"default\":0,\"field\":\"id\"},{\"type\":\"string\",\"optional\":false,\"field\":\"tenant_id\"},{\"type\":\"int64\",\"optional\":false,\"field\":\"goods_id\"},{\"type\":\"string\",\"optional\":false,\"field\":\"name\"},{\"type\":\"bytes\",\"optional\":false,\"name\":\"org.apache.kafka.connect.data.Decimal\",\"version\":1,\"parameters\":{\"scale\":\"2\",\"connect.decimal.precision\":\"10\"},\"field\":\"price\"},{\"type\":\"string\",\"optional\":false,\"field\":\"description\"},{\"type\":\"string\",\"optional\":false,\"field\":\"seller_phone\"},{\"type\":\"int64\",\"optional\":false,\"default\":0,\"field\":\"create_time\"},{\"type\":\"int64\",\"optional\":false,\"default\":0,\"field\":\"update_time\"},{\"type\":\"string\",\"optional\":false,\"field\":\"created_by\"},{\"type\":\"string\",\"optional\":false,\"field\":\"updated_by\"}],\"optional\":true,\"name\":\"topic-query_example-1.public.goods_info.Value\",\"field\":\"after\"},{\"type\":\"struct\",\"fields\":[{\"type\":\"string\",\"optional\":false,\"field\":\"version\"},{\"type\":\"string\",\"optional\":false,\"field\":\"connector\"},{\"type\":\"string\",\"optional\":false,\"field\":\"name\"},{\"type\":\"int64\",\"optional\":false,\"field\":\"ts_ms\"},{\"type\":\"string\",\"optional\":true,\"name\":\"io.debezium.data.Enum\",\"version\":1,\"parameters\":{\"allowed\":\"true,first,first_in_data_collection,last_in_data_collection,last,false,incremental\"},\"default\":\"false\",\"field\":\"snapshot\"},{\"type\":\"string\",\"optional\":false,\"field\":\"db\"},{\"type\":\"string\",\"optional\":true,\"field\":\"sequence\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"ts_us\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"ts_ns\"},{\"type\":\"string\",\"optional\":false,\"field\":\"schema\"},{\"type\":\"string\",\"optional\":false,\"field\":\"name\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"txId\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"lsn\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"xmin\"}],\"optional\":false,\"name\":\"io.debezium.connector.postgresql.Source\",\"version\":1,\"field\":\"source\"},{\"type\":\"struct\",\"fields\":[{\"type\":\"string\",\"optional\":false,\"field\":\"id\"},{\"type\":\"int64\",\"optional\":false,\"field\":\"total_order\"},{\"type\":\"int64\",\"optional\":false,\"field\":\"data_collection_order\"}],\"optional\":true,\"name\":\"event.block\",\"version\":1,\"field\":\"transaction\"},{\"type\":\"string\",\"optional\":false,\"field\":\"op\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"ts_ms\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"ts_us\"},{\"type\":\"int64\",\"optional\":true,\"field\":\"ts_ns\"}],\"optional\":false,\"name\":\"topic-query_example-1.public.goods_info.Envelope\",\"version\":2},\"payload\":{\"before\":null,\"after\":{\"id\":2,\"tenant_id\":\"2\",\"goods_id\":2,\"name\":\"商品2\",\"price\":\"AO7c\",\"description\":\"描述21\",\"seller_phone\":\"1778668378\",\"create_time\":1745652090247,\"update_time\":1745656764730,\"created_by\":\"admin10\",\"updated_by\":\"admin10\"},\"source\":{\"version\":\"3.1.1.Final\",\"connector\":\"postgresql\",\"name\":\"topic-query_example-1\",\"ts_ms\":1749021236252,\"snapshot\":\"false\",\"db\":\"query_example\",\"sequence\":\"[\\\"2225278376\\\",\\\"2225278496\\\"]\",\"ts_us\":1749021236252909,\"ts_ns\":1749021236252909000,\"schema\":\"public\",\"name\":\"goods_info\",\"txId\":1093,\"lsn\":2225278496,\"xmin\":null},\"transaction\":null,\"op\":\"u\",\"ts_ms\":1749024831994,\"ts_us\":1749024831994520,\"ts_ns\":1749024831994520000}}";
        long start = System.currentTimeMillis();

        durationRun(() -> {
            JSON.parseObject(val);

        });
        // durationRun(() -> {
        //     try (JsonParser parser = factory.createParser(val)){
        //         while(!parser.isClosed()){
        //             JsonToken jsonToken = parser.nextToken();
        //             if(JsonToken.FIELD_NAME.equals(jsonToken)){
        //                 if ("payload".equals(parser.currentName())) {
        //                     String s = parser.getText();
        //                     break;
        //                 }
        //             }
        //         }
        //     } catch (Exception e){
        //
        //     }
        // });
        durationRun(() -> {
            String payload = val.substring(val.indexOf("\"payload\":{") + 10, val.length() - 1);
            JSON.parseObject(payload, Payload.class);
        });
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(
                DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
        });
        Cc cc1 = objectMapper.readValue(val,
                new TypeReference<Cc>() {
                });
        System.out.println(JSON.toJSONString(cc1));
        durationRun(() -> {
            try {
                Cc cc = objectMapper.readValue(val,
                        new TypeReference<Cc>() {
                        });
            } catch (JsonProcessingException e) {
                System.out.println(e);
            }
        });
    }

    private static void durationRun(Runnable runnable) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 30000; i++) {
            runnable.run();
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    @Data
    public static class Cc {
        public Payload payload;
    }

    @Data
    public static class Payload {
        private JSONObject payload;
        private String op;
        private Long ts_ms;
        private Long ts_us;
        private Long ts_ns;
        private Long before;
        private Source source;
    }

    @Data
    public static class Source {
        private String db;
        private String schema;
        private String table;
        private String txId;
    }

    @Data
    public static class InnerPayload {
        private JSONObject before;
        private JSONObject after;
    }

    public void write(Long interfaceId, String msg, Exception exception) {
        write(interfaceId, msg + exception.toString());
    }

    public void write(Long interfaceId, String msg) {
        CompletableFuture.runAsync(() -> {
            log.error("错误日志 {}: {}", interfaceId, msg);
            healthInfoRepository.writeLog(interfaceId, msg);
        });
    }

    public void write(Long interfaceId, Object data) {
        write(interfaceId, JSONUtil.toJsonStr(data));
    }
}
